package com.example.demomybatis.controller;


import cn.hutool.core.lang.Pair;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demomybatis.entity.Person;
import com.example.demomybatis.service.IPersonService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhaoheng
 * @since 2023-07-07
 */
@RestController
@RequestMapping("/person")
@Slf4j
public class PersonController {
    @Resource
    IPersonService personService;

    @ApiOperation("插入person")
    @PostMapping("save")
    public String save(@RequestBody Person person) {
        log.info("person:{}", JSON.toJSONString(person));
        boolean b = personService.save(person);
        if (b) {
            return "创建成功";
        } else{
            return "创建失败";
        }
    }

    @ApiOperation("查询所有")
    @GetMapping("queryAll")
    public List<Person> queryAll() {
//        return personService.list();
        return personService.queryAllPerson();
    }

    @ApiOperation("修改出生日期")
    @PostMapping("updateBirthday")
    public boolean update(@RequestParam @ApiParam("姓名") String name, @RequestParam @ApiParam("出生日期") String localDate) {
        return personService.updateBirthday(name, localDate);
    }

    @ApiOperation("修改出生日期2")
    @PostMapping("updateBirthday2")
    public boolean update2(@RequestBody Person person) {
        System.out.println(JSON.toJSONString(person));
        return true;
    }

    @ApiOperation("根据姓名集合查询")
    @GetMapping("getByNames")
    public List<Person> queryByNames(@RequestParam List<String> names) {
        return personService.getByNames(names);
    }

    @ApiOperation("查询键值对")
    @GetMapping("queryId")
    public List<Pair<String, Integer>> queryId() {
        return personService.queryId();
    }

    @ApiOperation("根据id查询对象")
    @GetMapping("/queryById")
    public Person queryPersonById(@RequestParam @ApiParam(value = "id")Integer id) {
        Person person = personService.getById(id);
        log.info("person:{}", JSON.toJSONString(person));
        String name = person.getName();
        log.info("name:{}", name);
        return person;
    }

    @ApiOperation("分页查询")
    @GetMapping("/page")
    public Page<Person> page(int pageNum, int pageSize) {
        return personService.queryPage(pageNum, pageSize);
    }

}
